package net.chasing.retrofit.util.encode;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;

public class RSAUtils {
    //数字签名
    public static String sign(String data, byte[] privateKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
        return sign(data, keyFactory.generatePrivate(keySpec));
    }

    //数字签名
    public static String sign(String data, PrivateKey privateKey) throws Exception {
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initSign(privateKey);
        signature.update(data.getBytes());
        return byteToHex(signature.sign());
    }

    public static String byteToHex(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String tmp;
        for (byte value : b) {
            tmp = Integer.toHexString(value & 255);
            if (tmp.length() == 1) {
                hs.append("0").append(tmp);
            } else {
                hs.append(tmp);
            }
        }
        return hs.toString().toUpperCase();
    }
}